'use strict'
import EventEmitter from '../EventEmitter'
import Client from '../client'
import { compile } from './compile'
import Http from '../http'
import RoomData from '../roomdata'
export default class DyRoom extends EventEmitter {
  constructor (roomId) {
    super()
    this.roomId = roomId
    this.timer = null
    this.isInit = false
    this.data = null
    this.http = new Http()
    this.http.on('data', this.onHttpData.bind(this))
    this.http.on('error', this.onHttpError.bind(this))
    this.getRoomInfo()
  }
  getRoomInfo () {
    this.http.get('http://open.douyucdn.cn/api/RoomApi/room/' + this.roomId)
  }
  init () {
    this.client = new Client('openbarrage.douyutv.com', 8601)
    this.client.on('connect', this.onConnect.bind(this))
    this.client.on('data', this.onData.bind(this))
  }
  keepAlive () {
    this.timer = setInterval(() => {
      this.client.send(compile.toBuffer({
        type: 'keepalive',
        tick: Math.floor(new Date()
          .getTime() * 0.001)
      }))
      this.getRoomInfo()
    }, 45 * 1000)
  }
  onHttpData (obj) {
    if (this.isInit) {
      this.data.update(obj.data)
    } else {
      this.data = new RoomData('dy', obj.data.room_id)
      this.data.initRoom(obj.data)
      this.init()
      this.isInit = true
      this.emit('init', obj.data.room_id)
    }
  }
  onHttpError (text) {
    this.emit('init', '-1')
  }
  onConnect () {
    this.client.send(compile.toBuffer({
      type: 'loginreq',
      roomid: this.data.roomId
    }))
    this.keepAlive()
  }
  onData (info) {
    let obj = compile.toJson(info.data)
    let type = obj.type
    if (type === 'loginres') {
      this.client.send(compile.toBuffer({
        type: 'joingroup',
        rid: this.data.roomId,
        gid: '-9999'
      }))
    } else if (type === 'chatmsg' || type === 'dgb' || type === 'uenter') {
      var date = new Date()
      obj.serverdate = date.getHours() + ':' + date.getMinutes()
      this[type](obj)
    } else if (type === 'rss') {
      this.remove()
    }
  }
  uenter (data) {
    this.data.uenter(data)
  }
  chatmsg (data) {
    this.data.chatmsg(data)
  }
  dgb (data) {
    this.data.dgb(data)
  }
  remove () {
    this.data.close()
    clearTimeout(this.timer)
    this.client.close()
  }
}
